package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    //添加方法
    @PostMapping
    public R<String> add(@RequestBody com.itheima.entity.Category category){
        log.info(category.toString());

        //直接添加分类
        categoryService.save(category);

        return R.success("添加成功！！");
    }

    //分页查询
    @GetMapping("/page")
    public R<Page<com.itheima.entity.Category>> selectByPage(Integer page,Integer pageSize){
        log.info(page+":"+pageSize);
        Page<com.itheima.entity.Category> page1=new Page<>(page,pageSize);
        LambdaQueryWrapper<com.itheima.entity.Category> qw=new LambdaQueryWrapper<>();
        qw.orderByDesc(com.itheima.entity.Category::getSort);
        Page<Category> page2 = categoryService.page(page1, qw);
        if (page2==null){
            return R.error("查询失败！");
        }
        return R.success(page2);
    }

    //修改方法
    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info(category.toString());
        //直接修改
        boolean b = categoryService.updateById(category);
        return R.success("修改状态成功！");
    }

    //删除方法
    @DeleteMapping
    public R<String> delete(Long id){
        log.info(id.toString());
        categoryService.removeById(id);
        return R.success("删除成功！");
    }

    //查询方法
    @GetMapping("/list")
    public R<List<Category>> list(){
        List<Category> list1 = categoryService.list();
        return R.success(list1);
    }

}
